<template>
  <el-dialog
    v-el-drag-dialog
    :title="type === 'add' ? '新增仓库信息' : '编辑仓库信息'"
    :visible.sync="visible"
    width="500px"
    @closed="reset"
  >
    <el-form ref="dataForm" class="form" :rules="rules" :model="temp" label-position="right" label-width="80px" style="margin: 0 50px;">
      <el-form-item label="仓库编码" prop="storeCode">
        <el-input v-model.trim="temp.storeCode" :maxlength="20" :disabled="type === 'edit'" :style="type === 'add' ? 'width: 150px' : null" clearable />
        <el-button v-if="type === 'add'" type="primary" size="small" plain @click.prevent="getCode">获取</el-button>
      </el-form-item>
      <el-form-item label="仓库名称" prop="storeName">
        <el-input v-model="temp.storeName" />
      </el-form-item>
      <el-form-item label="关联类型" prop="reType">
        <el-select v-model="temp.reType" placeholder="请选择" :disabled="type === 'edit'" style="width: 100%;" @change="reTypeChange">
          <el-option
            v-for="item in reTypeMap"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item v-if="temp.reType === 1" label="门市" prop="reId">
        <el-tree-select
          v-model="temp.reId"
          :disabled="type === 'edit'"
          class="tree-select"
          :select-params="{
            clearable: false,
            placeholder: '请选择'
          }"
          :tree-params=" {
            'default-expand-all': true,
            'expand-on-click-node': false,
            'highlight-current': true,
            props:{
              value:'orgId',
              label: 'orgName',
            },
            data: treeData
          }"
          @node-click="selectTreeChange"
        />
      </el-form-item>
      <el-form-item v-if="temp.reType === 2" label="配送员" prop="reId">
        <el-select v-model="temp.reId" :disabled="type === 'edit'" :loading="$loadingPlugin.getOwnerList" style="width: 100%;" placeholder="请选择">
          <el-option
            v-for="item in ownerList"
            :key="item.userId"
            :label="item.userName"
            :value="item.userId"
          />
        </el-select>
      </el-form-item>
      <el-form-item v-if="temp.reType === 3" label="气站" prop="reId">
        <el-tree-select
          v-model="temp.reId"
          :disabled="type === 'edit'"
          class="tree-select"
          :select-params="{
            clearable: false,
            placeholder: '请选择'
          }"
          :tree-params=" {
            'default-expand-all': true,
            'expand-on-click-node': false,
            'highlight-current': true,
            props:{
              value:'orgId',
              label: 'orgName',
            },
            data: treeData
          }"
          @node-click="selectTreeChange"
        />
      </el-form-item>
      <el-form-item v-if="temp.reType === 6" label="其他" prop="reId">
        <el-tree-select
          v-model="temp.reId"
          :disabled="type === 'edit'"
          class="tree-select"
          :select-params="{
            clearable: false,
            placeholder: '请选择'
          }"
          :tree-params=" {
            'default-expand-all': true,
            'expand-on-click-node': false,
            'highlight-current': true,
            props:{
              value:'orgId',
              label: 'orgName',
            },
            data: treeData
          }"
          @node-click="selectTreeChange"
        />
      </el-form-item>
      <el-form-item label="主管" prop="directorId">
        <el-select v-model="temp.directorId" :loading="$loadingPlugin.getOwnerList" style="width: 100%;" placeholder="请选择">
          <el-option
            v-for="item in ownerList"
            :key="item.userId"
            :label="item.userName"
            :value="item.userId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="联系电话" prop="directorTel">
        <el-input v-model="temp.directorTel" />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="visible = false">
        关闭
      </el-button>
      <el-button :loading="$loadingPlugin.add || $loadingPlugin.edit" type="primary" @click="success">
        保存
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
  import { warehouseAdd, queryOrgCode, queryOwnerList, queryDelivermanList } from '@/api'
  import { mapGetters } from 'vuex'
  import getTreeData from '@/utils/jsonTree'
  import { isWildPhone } from '@/utils'

  export default {
    name: 'add',
    props: {
      reTypeMap: {
        type: Array,
        required: true
      }
    },
    data() {
      const validateTruckCode = (rule, value, callback) => {
        if (value !== '') {
          if (!isWildPhone(value)) {
            callback(new Error('联系电话格式输入不正确，请重新输入'))
          }
        } else {
          callback()
        }
        callback()
      }
      return {
        visible: false,
        type: 'add',
        currentOrg: null,
        treeData: [],
        ownerList: [],
        delivermanList: [],
        temp: {
          storeCode: '',
          storeName: '',
          reType: 1,
          reId: '',
          directorTel: '',
          directorId: ''
        },
        rules: {
          storeName: [{ required: true, message: '请输入仓库名称', trigger: 'change' }],
          reType: [{ required: true, message: '请选择关联类型', trigger: 'change' }],
          reId: [{ required: true, message: `请选择${this.reTypeLabel}`, trigger: 'change' }],
          directorId: [{ required: true, message: '请选择主管', trigger: 'change' }],
          directorTel: [{ validator: validateTruckCode, trigger: 'blur' }]
        }
      }
    },
    computed: {
      ...mapGetters([
        'orgList', 'corpSettingData'
      ]),
      reTypeLabel: function() {
        let label = ''
        switch (this.temp.reType) {
        case 1:
          label = '门市'
          break
        case 2:
          label = '配送员'
          break
        case 3:
          label = '气站'
          break
        case 6:
          label = '其他'
          break
        }
        return label
      }
    },
    methods: {
      open(temp) {
        this.getTreeData()
        return new Promise(resolve => {
          this.resolve = resolve
          this.visible = true
          if (temp) {
            this.temp = Object.assign(this.temp, temp, {
              address: [temp.provinceCode, temp.cityCode, temp.countyCode, temp.streetCode]
            })
            this.type = 'edit'
          }
        })
      },
      // 获取仓库编码
      async getCode() {
        const res = await queryOrgCode({
          codeType: 4
        })
        this.temp.storeCode = res.data
      },
      // 获取所属机构数据
      async getTreeData() {
        const data = this.orgList.map(item => ({
          label: item.name,
          ...item
        }))
        this.treeData = getTreeData(data)
      },
      // 获取处理人列表
      async getOwnerList() {
        const b = this.corpSettingData.sp1 >> 2 & 0x01
        const orgId = this.currentOrg ? this.currentOrg.orgId : -1
        const res = await queryOwnerList({
          orgId,
          corpparm1: b
        })
        this.ownerList = res.data
      },
      // 选择所属机构
      selectTreeChange(value) {
        this.currentOrg = value
        this.getOwnerList()
      },
      // 关联类型变化
      async reTypeChange(value) {
        if (value === 2) {
          const res = await queryDelivermanList()
          this.delivermanList = res.data
        }
      },
      success() {
        this.$refs.dataForm.validate(valid => {
          if (!valid) return
          const _this = this
          this.$confirm(`确认保存仓库信息？`, '提示', {
            type: 'info'
          }).then(() => {
            const org = this.orgList.find(item => item.orgId === this.temp.reId)
            const match = this.ownerList.find(item => item.userId === this.temp.directorId)
            const params = {
              storeName: _this.temp.storeName,
              reType: _this.temp.reType,
              directorId: _this.temp.directorId,
              director: match.userName,
              directorTel: _this.temp.directorTel
            }
            if (org) {
              params.reId = org.orgId
              params.rName = org.orgName
            }
            if (_this.type === 'add') {
              params.storeCode = this.temp.storeCode
              _this.add(params)
            } else {
              params.storeId = this.temp.storeId
              _this.add(params)
            }
          })
        })
      },
      async add(params) {
        await warehouseAdd(params)
        this.resolve()
        this.visible = false
        this.$notify({
          title: '提示',
          message: '仓库信息保存成功',
          type: 'success',
          duration: 2000
        })
      },
      reset() {
        this.type = 'add'
        this.temp = {
          storeCode: '',
          storeName: '',
          reType: 1,
          reId: '',
          directorTel: '',
          directorId: ''
        }
        this.$nextTick(() => {
          this.$refs.dataForm.clearValidate()
        })
      }
    }
  }
</script>

<style lang="scss" scoped>

</style>
